<template>
    <div class="transferBox">
        <header>
            <div class="left">
                <span class="title">信息</span>
            </div>
            <div class="right">
                <i class="iconfont icon-guanbi" @click="handleCancel"></i>
            </div>
        </header>
        <main>
            <div class="left transfer-item">
                <el-scrollbar style="height: 420px">
                    <el-tree class="eq-tree" node-key="id" ref="leftTree" :data="leftTreeData" :props="defaultProps"
                        show-checkbox @check="leftTreeCheck" style="max-width: 600px" />
                </el-scrollbar>
            </div>
            <div class="center">
                <div class="arrow-top arrow" :class="{ forbidBtn: isTopBtnForbid }" @click="handleAdd">
                    <el-icon>
                        <ArrowRightBold />
                    </el-icon>
                </div>
                <div class="arrow-bottom arrow" :class="{ forbidBtn: isBottomBtnForbid }">
                    <el-icon>
                        <ArrowLeftBold @click="handleRemove" />
                    </el-icon>
                </div>
            </div>
            <div class="right transfer-item">
                <el-scrollbar style="height: 420px">
                    <el-tree class="eq-tree" node-key="id" ref="rightTree" :data="rightTreeData" :props="defaultProps"
                        show-checkbox @check="rightTreeCheck" style="max-width: 600px" />
                </el-scrollbar>
            </div>
        </main>
        <footer>
            <span class="resetBtn" @click="handleCancel">取消</span>
            <span class="searchBtn" @click="handleRecover">恢复默认</span>
            <span class="searchBtn" @click="handleConfirm">确定</span>
        </footer>
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';

import { apiFn, deepCopy } from '@/utils/utilFns';

import * as local from '@/utils/cache/localStorage';
import * as server from '@/api/modules/technicalDataAnalysis';

const props = defineProps({
    selectedIds: {
        type: Array,
        default: () => [],
    },
});

const emit = defineEmits(['closeDialog', 'restore']);

const defaultProps = {
    children: 'childrenList',
    label: 'text'
};

const defaultIds = ref([]);

const leftTree = ref(null);
const rightTree = ref(null);
const leftTreeData = ref([]);
const rightTreeData = ref([]);
const leftTreeCheckedData = ref({});
const rightTreeCheckedData = ref({});

const isTopBtnForbid = ref(true);
const isBottomBtnForbid = ref(true);

onMounted(() => {
    getCustomTreeData();
});

// 获取自定义配置数据
const getCustomTreeData = () => {
    const params = {
        equal: {
            type: '1',
            userId: local.getUser().id,
        },
    };

    apiFn(server.getUserCunstomTreeData, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                const datas = getDefaultConfigData(data);
                
                leftTreeData.value = datas;
                getRightTreeData(deepCopy(datas));
            }
        })
        .catch(() => {
            datas.value = [];
        });
};

// 获取用户默认配置项数据
const getDefaultConfigData = (datas) => {
    const ids = [];

    const recusive = (datas) => {
        datas.forEach((item) => {
            const { childrenList, id, disable } = item;
            item.disabled = disable === 'false' ? false : true;

            if (item.parentId === '0') {
                item.parentId = 0;
            }

            if (childrenList.length > 0) {
                recusive(childrenList);
            } else {
                item.disabled && ids.push(id);
            }
        });
    };

    recusive(datas);
    defaultIds.value = ids;

    return datas;
};

// 获取右侧树数据
const getRightTreeData = async (data) => {
    const { selectedIds } = props;

    rightTreeData.value = data;
    rightTree.value.setCheckedKeys(selectedIds);

    await nextTick();
    let halfNodes = rightTree.value.getHalfCheckedNodes();
    const nodes = rightTree.value.getCheckedNodes();

    halfNodes.forEach((item) => {
        item.childrenList = [];
        const children = nodes.filter((node) => node.parentId === item.id);
        item.childrenList = children;
    });

    rightTree.value.setCheckedKeys([]);
    rightTreeData.value = halfNodes;
};

// 左侧树复选框选中事件
const leftTreeCheck = (data1, data2) => {
    const { checkedNodes } = data2;

    if (checkedNodes.length > 0) {
        isTopBtnForbid.value = false;
        leftTreeCheckedData.value = data2;
    } else {
        isTopBtnForbid.value = true;
    }
};

// 右侧树复选框选中事件
const rightTreeCheck = (data1, data2) => {
    const { halfCheckedNodes, checkedNodes } = data2;

    if (checkedNodes.length > 0) {
        isBottomBtnForbid.value = false;
        rightTreeCheckedData.value = data2;
    } else {
        isBottomBtnForbid.value = true;
        return;
    }

    let parentNodes = deepCopy(halfCheckedNodes);
    parentNodes.forEach((parentNode) => {
        const children = checkedNodes.filter(
            (node) => node.parendId === parentNode.id
        );
        parentNode.childrenList = children;
    });
};

// 取消
const handleCancel = () => {
    emit('closeDialog');
};

// 添加
const handleAdd = () => {
    if (isTopBtnForbid.value) return;

    const { halfCheckedNodes, checkedNodes, checkedKeys } = leftTreeCheckedData.value;

    let parentNodes = deepCopy([...halfCheckedNodes, ...checkedNodes]).filter(
        (item) => item.parentId === 0
    );
    parentNodes.forEach((parentNode) => {
        const children = checkedNodes.filter(
            (node) => node.parentId === parentNode.id
        );
        parentNode.childrenList = children;

        // 左侧树数据处理
        const lIndex = leftTreeData.value.findIndex(
            (item) => item.id === parentNode.id
        );
        leftTreeData.value[lIndex].childrenList = leftTreeData.value[lIndex].childrenList.filter((item) => !checkedKeys.includes(item.id));

        if (leftTreeData.value[lIndex].childrenList.length === 0) {
            leftTreeData.value.splice(1, lIndex);
        }

        // 右侧树数据处理
        const rIndex = rightTreeData.value.findIndex(
            (item) => item.id === parentNode.id
        );
        if (rIndex > 0) {
            rightTreeData.value[rIndex].childrenList = [
                ...rightTreeData.value[rIndex].childrenList,
                ...children,
            ];
        } else {
            rightTreeData.value.push(parentNode);
        }
    });

    isTopBtnForbid.value = true;
};

// 移除
const handleRemove = () => {
    if (isBottomBtnForbid.value) return;

    const { halfCheckedNodes, checkedNodes, checkedKeys } =
        rightTreeCheckedData.value;

    let parentNodes = deepCopy([...halfCheckedNodes, ...checkedNodes]).filter(
        (item) => item.parentId === 0
    );
    parentNodes.forEach((parentNode) => {
        const children = checkedNodes.filter(
            (node) => node.parentId === parentNode.id
        );
        parentNode.childrenList = children;

        // 右侧树数据处理
        const rIndex = rightTreeData.value.findIndex(
            (item) => item.id === parentNode.id
        );
        rightTreeData.value[rIndex].childrenList = rightTreeData.value[rIndex].childrenList.filter((item) => !checkedKeys.includes(item.id));

        if (rightTreeData.value[rIndex].childrenList.length === 0) {
            rightTreeData.value.splice(1, rIndex);
        }

        // 左侧树数据处理
        const lIndex = leftTreeData.value.findIndex(
            (item) => item.id === parentNode.id
        );
        if (lIndex > 0) {
            leftTreeData.value[lIndex].childrenList = [
                ...leftTreeData.value[lIndex].childrenList,
                ...children,
            ];
        } else {
            leftTreeData.value.push(parentNode);
        }
    });

    isBottomBtnForbid.value = true;
};

// 恢复默认
const handleRecover = () => { 
    const ids = defaultIds.value;
    updateUserCustomData(ids);
};

// 确定
const handleConfirm = () => { 
    const ids = [];
    const recusive = (datas) => {
        datas.forEach(data => {
            const { childrenList, id } = data;
            if(childrenList.length > 0){
                recusive(childrenList);
            }else{
                ids.push(id);
            }
        });
    };
    
    recusive(rightTreeData.value);
    updateUserCustomData(ids);
};

// 更新用户自定义配置数据
const updateUserCustomData = (ids) => {
    const params = {
        equal: {
            userId: local.getUser().id,
            customIds: ids.join(','),
            type: '1'
        }
    };
    apiFn(server.updateUserCustomData, params)
        .then((res) => {
            const { code } = res;
            if (code === '200') {
                ElMessage.success('更新成功！');
                emit('restore');
            }
        }).catch(() => {
            ElMessage.success('更新失败！');
        });
};
</script>

<style lang="scss">
@import url('./Transfer.scss');

.eq-tree {
    background: var(--eq-dialog-transfer-bg-color);
    color: var(--eq-font-color);

    .el-tree-node__content:hover {
        background-color: var(--eq-dialog-hover);
    }

    .el-tree-node:focus>.el-tree-node__content {
        background-color: var(--eq-dialog-hover);
    }
}
</style>
